package cn.org.xuanzp.nty.client;

import cn.hutool.crypto.digest.MD5;
import cn.org.xuanzp.nty.client.handler.NettyClientHandler;
import cn.org.xuanzp.nty.utils.NettyClientUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Base64;

/**
 * @Classname Client
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/9/24 22:48
 * @Created by xuanzp
 */
public class Client {
    public static ChannelHandlerContext ctx;

    private String host;// 当前netty客户端连接的主机地址
    private int port;// 当前netty客户端连接的端口
    private Channel channel;
    private EventLoopGroup mainGroup;
    public Client(String host, int port) {
        this.host = host;
        this.port = port;
        this.mainGroup = new NioEventLoopGroup();
    }


    public Channel getChannel() {
        return channel;
    }

    // 启动当前netty服务器的操作
    public void start() throws Exception {
        Bootstrap b = new Bootstrap(); // (1)
        b.group(mainGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)

        NettyClientHandler handler = new NettyClientHandler(this);

        b.handler(new NettyClientInitializer(handler));


        // Start the client.
        ChannelFuture future = b.connect(host, port).sync(); // (5)
        // 添加监听器，用于判断是否连接成功或者连接失败
        future.addListener(new ChannelFutureListener() {

            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("连接服务器成功");

                } else {
                    System.out.println("连接服务器失败");
                    future.cause().printStackTrace();
                    mainGroup.shutdownGracefully(); // 关闭线程组
                }

            }
        });
        this.channel = future.channel();

    }


    public void send(Object obj) {
        Channel channel = this.getChannel();
        System.out.println("channel:::"+channel.isActive()+" "+channel.isOpen());
        ChannelFuture channelFuture = channel.writeAndFlush(obj);
    }

    // 客户端的被动关闭操作,由服务器发起操作
    public void close() {
        NettyClientUtil.removeCtx(getServerId());
        mainGroup.shutdownGracefully();// 关闭当前的线程组
    }

    // 客户端的被动关闭操作,由服务器发起操作
    public void removeCtx() {
        NettyClientUtil.removeCtx(getServerId());
    }


    // 客户端的主动关闭操作
    public void open(ChannelHandlerContext ctx) {
        NettyClientUtil.addCtx(getServerId(),ctx);
    }


    public String getServerId() {
        return MD5.create().digestHex(host+":"+port);
    }

}
